<template>
  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-space type="small">
          <a-input-search
              v-model:value="searchName"
              placeholder="请输入名称"
              enter-button="搜索"
              size="large"
              style="width: 400px"
              allow-clear
              @search="handleSearch"
          />
          <a-button type="primary" @click="add()" size="large">
            新增
          </a-button>
        </a-space>
      </p>
      <a-table :columns="columns"
               :row-key="record => record.id"
               :data-source="users"
               :pagination="pagination"
               :loading="loading"
               @change="handleTableChange"
      >
        <template #cover="{ text:cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:category="{ text:record }">
          <span>{{ getCategoryName(record.category1Id) }}/{{ getCategoryName(record.category2Id) }}</span>
        </template>
        <template v-slot:action="{text,record}">
          <a-space type="small">
            <a-button type="primary" @click="resetPassword(record)">
              重置密码
            </a-button>
            <a-button type="primary" @click="edite(record)">
              编辑
            </a-button>
            <a-button type="danger" @click="deleteById(record.id)">
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
      title="用户表单"
      v-model:visible="modalVisible"
      :confirm-loading="modalLoading"
      @ok="modalHandleOk"
  >
    <a-form :model="user" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="登陆名">
        <a-input v-model:value="user.loginName" :disabled="!!user.id"/>
      </a-form-item>
      <a-form-item label="昵称">
        <a-input v-model:value="user.name" />
      </a-form-item>
      <a-form-item label="密码" v-show="!user.id">
        <a-input v-model:value="user.password" type="password"/>
      </a-form-item>
    </a-form>
  </a-modal>


  <a-modal
      title="重置密码"
      v-model:visible="resetmodalVisible"
      :confirm-loading="resetmodalLoading"
      @ok="modalHandleResetOk"
  >
    <a-form :model="user" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="新密码">
        <a-input v-model:value="user.password" type="password"/>
      </a-form-item>
    </a-form>
  </a-modal>

</template>

<script lang="ts">
import {createVNode, defineComponent, onMounted, ref} from 'vue';
import axios from 'axios';
import {message, Modal} from "ant-design-vue";
import {ExclamationCircleOutlined} from "@ant-design/icons-vue";

declare let hexMd5: any;
declare let KEY: any;


export default defineComponent({
  name: 'AdminUser',
  setup() {

    const users = ref();
    const pagination = ref({
      current: 1,
      pageSize: 8,
      total: 0
    });
    const loading = ref(false);

    const columns = [
      {
        title: '登陆名',
        dataIndex: 'loginName'
      },
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '密码',
        dataIndex: 'password'
      },
      {
        title: '操作',
        key: 'action',
        slots: { customRender: 'action' }
      }
    ];

    // 模态框
    const modalVisible = ref<boolean>(false);
    const modalLoading = ref<boolean>(false);

    // 表单
    const user = ref();

    // 搜索
    const searchName = ref();

    /**
     * 修改
     * @param record
     */
    const edite = (record: any) => {
      modalVisible.value = true;
      user.value = record;
    };
    /**
     * 删除
     * @param record
     */
    const deleteById = (record: any) => {
      Modal.confirm({
        title: () => '你确定要选择删除以下文档吗？',
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => '被删除后文档将无法恢复',
        onOk() {
          axios.delete("/user/delete", {
            params: {
              id: record
            }
          }).then((response) => {
            const data = response.data;
            if (data.success) {
              handleQuery({
                page: pagination.value.current,
                size: pagination.value.pageSize
              });
            }
          });
        },
        // eslint-disable-next-line @typescript-eslint/no-empty-function
        onCancel() {},
      });
    };

    /**
     * 新增
     * @param record
     */
    const add = () => {
      modalVisible.value = true;
      user.value = {};
    };

    /**
     * 搜索框查询
     */
    const handleSearch = () => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize,
        loginName: searchName.value
      });
    }

    const modalHandleOk = () => {
      modalLoading.value = true;
      user.value.password = hexMd5(user.value.password + KEY);
      axios.post("/user/save", user.value).then((response) => {
        modalLoading.value = false;
        const data = response.data;

        if (data.success) {
          modalVisible.value = false;

          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        }else {
          message.error(data.message);
        }

      });

    }

    /**
     * 数据查询
     **/
    const handleQuery = (params: any) => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      users.value = [];
      axios.get("/user/list", {
        params: params
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        users.value = data.content.list;

        // 重置分页参数
        pagination.value.current = params.page;
        pagination.value.total = data.content.total;
      });
    };

    /**
     * 表格点击页码时触发
     */
    const handleTableChange = (pagination: any) => {
      handleQuery({
        page: pagination.current,
        size: pagination.pageSize,
        name: searchName.value
      });
    };

    // 重置密码
    const resetmodalVisible = ref<boolean>(false);
    const resetmodalLoading = ref<boolean>(false);

    /**
     * 重置密码
     * @param record
     */
    const resetPassword = (record: any) => {
      resetmodalVisible.value = true;
      user.value = record;
      user.value.password = null;
    };

    const modalHandleResetOk = () => {
      resetmodalLoading.value = true;

      user.value.password = hexMd5(user.value.password + KEY);

      axios.post("/user/resetPassword", user.value).then((response) => {
        resetmodalLoading.value = false;
        const data = response.data;

        if (data.success) {
          resetmodalVisible.value = false;

          handleQuery({
            page: pagination.value.current,
            size: pagination.value.pageSize
          });
        }else {
          message.error(data.message);
        }

      });

    }


    onMounted(() => {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      });
    });



    return {
      users,
      pagination,
      columns,
      loading,
      handleTableChange,
      //模态框
      modalVisible,
      modalLoading,
      edite,
      deleteById,
      modalHandleOk,
      //表单
      user,
      add,
      // 搜索
      handleSearch,
      searchName,

      // 重置密码
      resetmodalVisible,
      resetmodalLoading,
      resetPassword,
      modalHandleResetOk
    }
  }
});
</script>

<style scoped>
img {
  width: 50px;
  height: 50px;
}
</style>
